package com.guotong.common.exception;

import com.guotong.utils.R;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.DuplicateFormatFlagsException;


/**
 * 异常处理器
 * @author H
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * log4j
     */
    Logger logger = LogManager.getLogger(this.getClass());

    /**
     *  处理自定义异常
     */
    @ExceptionHandler(GlobalException.class)
    public R handleException(GlobalException e){
        logger.error(e.getMessage());

        R r = new R();
        r.put("code",e.getCode());
        r.put("msg",e.getMsg());
        return r;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public R noHandlerFoundException(Exception e){
        logger.error(e.getMessage());
        return R.error(404,"路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e){
        logger.error(e.getMessage());
        return R.error("数据库中已存在该记录");
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e){
        logger.error(e.getMessage());
        return R.error();
    }


}
